<?php
/**
* 
*/
class UserModel extends MY_Model
{
	
	public function __construct(){
		
		parent::__construct();
		$this->table = 'user';
	}


	//获取会员数据
	public function get_user_data($term=array(),$page=1,$size=20)
	{
		$where = ' where 1';

		if (isset($term['keyword']) && !empty($term['keyword'])) {

			$where .= " AND (nickname LIKE '%".$term['keyword']."%' OR mobile LIKE '%".$term['keyword']."%')";
		}

		$query = $this->db->query("SELECT id, nickname, headimg, mobile, sex, label, remarks, disabled FROM ".$this->db->dbprefix . $this->table.$where." ORDER BY id DESC LIMIT ".($page-1)*$size.",".$size);

		$data = $query->result_array();

		foreach ($data as $key => $value) {
			$data[$key]['sex'] = $value['sex'] == 0 ? '未知' : ($value['sex'] == 1 ? '男' : '女');
		}

		$query = $this->db->query("select COUNT(*)  as num from ".$this->db->dbprefix . $this->table." as c".$where);
		$row = $query->row_array();

		//总数
		$count = $row['num'];
		//总页数
		$pages = ceil($count/$size);
		
		return array('list'=>$data,'count'=>$count, 'pages'=>$pages);

	}


	//
	public function user_data_row($user_id)
	{
		$query = $this->db->query("SELECT * FROM ".$this->db->dbprefix . $this->table." where id = '$user_id'");
		$data = $query->row_array();

		$data['addtime'] = date('Y-m-d H:i:s',$data['addtime']);
		$data['user_id'] = $data['id'];

		return $data;
	}


	//消费情况
	public function get_user_consu($user_id)
	{
		//消费总额
		$query = $this->db->query("SELECT SUM(price) as total_num FROM nmp_user_card_log where user_id = '$user_id'");
		$res = $query->row_array();
		$data['total_num'] = $res['total_num'] ? $res['total_num'] : 0;

		//本月消费
		$start = date('Y-m-01 00:00:00');
		$end = date('Y-m-d H:i:s');
		$query = $this->db->query("SELECT SUM(price) as month_total FROM nmp_user_card_log where user_id = '$user_id' AND addtime >= unix_timestamp('$start') AND addtime <= unix_timestamp('$end')");
		$res = $query->row_array();
		$data['month_total'] = $res['month_total'] ? $res['month_total'] : 0;

		//上课数
		$query = $this->db->query("SELECT COUNT(*) as course_num FROM nmp_user_appoint where user_id = '$user_id' AND addtime >= unix_timestamp('$start') AND addtime <= unix_timestamp('$end') AND status = 1");
		$res = $query->row_array();

		$data['course_num'] = $res['course_num'];
		$sql = "SELECT SUM(card.num) as course_total FROM nmp_user_card as card LEFT JOIN nmp_course AS c ON c.id = card.cid WHERE card.user_id = '{$user_id}' AND c.id IS NOT NULL AND c.`status` = 1";
		$query = $this->db->query($sql);
		$course = $query->row_array();

		$query = $this->db->query("SELECT SUM(num) as appoint_num FROM nmp_user_appoint where user_id = '$user_id' AND status = 1");
		$appoint = $query->row_array();
		$data['balance'] = $course['course_total'] - $appoint['appoint_num'];

		//已购卡数
		$query = $this->db->query("SELECT count(*) as card_num FROM nmp_user_card as card LEFT JOIN nmp_course AS c ON c.id = card.cid where card.user_id = '$user_id' AND c.id IS NOT NULL AND c.`status` = 1");
		$res = $query->row_array();
		$data['card_num'] = $res['card_num'];

		return $data;

	}


	//课程情况
	public function get_course_card($user_id)
	{
		$sql = "SELECT card.card_name as name, uc.num ,uc.total_num , uc.card_id FROM nmp_user_card as uc ".
			"LEFT JOIN nmp_course_card as card ON uc.card_id = card.id ".
			"LEFT JOIN nmp_course as c ON c.id = card.course_id ".
			"WHERE uc.user_id = '{$user_id}' AND c.id IS NOT NULL AND c.`status` = 1 ORDER BY uc.addtime DESC";
			
		$query = $this->db->query($sql);
		$res = $query->result_array();

		foreach ($res as $key => $value) 
		{
			$query = $this->db->query("SELECT SUM(num) as appoint_num FROM nmp_user_appoint WHERE card_id = $value[card_id] AND user_id = '$user_id' AND status = 1");
			$appoint = $query->row_array();

			$num = $value['num'] - $appoint['appoint_num'];
			$res[$key]['num'] = $num;
			$res[$key]['status'] = $num == 0 || $num < 0 ? '<font style="color:#ccc;">结停</font>' : '<font style="font-weight: bold;">正常</font>';
		}

		return $res;
	}


	//获取消费记录
	public function consu_log($user_id)
	{
		$query = $this->db->query("SELECT lg.price, lg.num, lg.addtime, c.card_name as name, lg.info FROM nmp_user_card_log as lg 
			LEFT JOIN nmp_course_card as c ON lg.card_id = c.id WHERE lg.user_id = '$user_id' ORDER BY lg.addtime DESC");
		$res = $query->result_array();

		foreach ($res as $key => $value) {
			$res[$key]['addtime'] = date('m-d H:i:s',$value['addtime']);
			$res[$key]['add_time'] = date('Y-m-d H:i:s',$value['addtime']);
		}

		return $res;
	}


	//获取折线图数据
	public function appoint_data($user_id,$dtnum = 30)
	{
		$date_arr = array();
		$appoint_arr = array();

		if (!is_numeric($dtnum)) 
		{
			//处理日期
			$d1 = substr($dtnum,0,10);
			$d2 = substr($dtnum,-10);
			$dlist = $this->getDateFromRange($d1,$d2);

			for ($i=0; $i < count($dlist); $i++) 
			{
				$date_arr[] = substr($dlist[$i],-5);

				$start = date('Y-m-d 00:00:00',strtotime($dlist[$i]));
				$end = date('Y-m-d 00:00:00',strtotime($dlist[$i])+86400);

				$query = $this->db->query("SELECT count(*) as appoint_num FROM nmp_user_appoint WHERE addtime >= unix_timestamp('$start') AND addtime <= unix_timestamp('$end') AND user_id = '$user_id'");
				$res = $query->row_array();

				$appoint_arr[] = $res['appoint_num'];
			}
		}
		else
		{
			for ($i=$dtnum; $i > 0; $i--) 
			{
				$date_arr[] = date('m-d',strtotime('-'.$i.' day'));

				$start = date('Y-m-d 00:00:00',strtotime('-'.$i.' day'));
				$end = date('Y-m-d 00:00:00',strtotime('-'.($i-1).' day'));

				$query = $this->db->query("SELECT count(*) as appoint_num FROM nmp_user_appoint WHERE addtime >= unix_timestamp('$start') AND addtime <= unix_timestamp('$end') AND user_id = '$user_id'");
				$res = $query->row_array();

				$appoint_arr[] = $res['appoint_num'];
			}

		}

		$data['date_list'] = $date_arr;
		$data['appoint_num'] = $appoint_arr;

		return $data;

	}



	/**
	 * 获取指定日期段内每一天的日期
	 * @param  Date  $startdate 开始日期
	 * @param  Date  $enddate   结束日期
	 * @return Array
	 */
	function getDateFromRange($startdate, $enddate)
	{
	    $stimestamp = strtotime($startdate);
	    $etimestamp = strtotime($enddate);

	    // 计算日期段内有多少天
	    $days = ($etimestamp-$stimestamp)/86400+1;

	    // 保存每天日期
	    $date = array();
	    for($i=0; $i<$days; $i++){
	        $date[] = date('Y-m-d', $stimestamp+(86400*$i));
	    }

	    return $date;
	}


	//预约记录
	public function bespeak_data($user_id)
	{
		$query = $this->db->query("SELECT ap.*,c.name,ch.nickname,c.type_id FROM nmp_user_appoint as ap 
			LEFT JOIN nmp_course as c ON ap.cid = c.id 
			JOIN nmp_coach ch ON ap.mid = ch.id WHERE ap.user_id = '$user_id' ORDER BY ap.addtime DESC");
		$res = $query->result_array();

		foreach ($res as $key => $value) 
		{
			$res[$key]['addtime'] = date('Y-m-d',$value['addtime']);
			$res[$key]['status'] = $value['status'] == 1 ? '<font style="color:#0cc3aa">已签到</font>' : ($value['status'] == 2 ? '<font style="color:#ccc">已取消</font>' : '<font style="color:#fabf2d">未签到</font>');
			$res[$key]['type'] = $value['type_id'] == 1 ? '团教' : '私教';
		}


		return $res;

	}


	//训练计划
	public function plan_data($user_id)
	{
		$query = $this->db->query("SELECT t.id, t.name, c.nickname FROM nmp_course_train as t 
			LEFT JOIN nmp_coach as c ON t.coach_id = c.id WHERE t.user_id = '$user_id' ORDER BY t.addtime DESC");
		$res = $query->result_array();

		return $res;

	}

    /**
     * 训练计划详情
     * @param $plan_id
     * @return mixed
     */
	public function plan_info($plan_id)
    {
        $query = $this->db->query("SELECT stime,type,info FROM nmp_course_train_info WHERE tid = '$plan_id'");
        $res = $query->result_array();

        foreach ($res as $k=>$v){
            $info = json_decode($v['info'],'true');

            $res[$k]['info'] = $info;
            //动作
            if ($v['type'] == 'dongzuo'){
                for ($i = 0;$i < count($info);$i++){
                    if (isset($info[$i]['id'])){
                        $res[$k]['info'][$i]['name'] = $this->get_movement($info[$i]['id']);
                    }
                }

            }
            //课程
            if ($v['type']=='kecheng'){
                $course = implode(',',$info);
                $res[$k]['info'] = $this->get_course($course);
            }
        }

        return $res;
    }

    /**
     * 获取动作
     * @param $ids
     * @return mixed
     */
    public function get_movement($ids)
    {
        $query = $this->db->query("SELECT name FROM nmp_sport WHERE id IN ($ids)");
        $movement = $query->row_array();

        return $movement['name'];

    }

    /**
     * 获取课程
     * @param $ids
     * @return mixed
     */
    public function get_course($ids)
    {
        $query = $this->db->query("SELECT title FROM nmp_course WHERE id IN ($ids)");
        $course = $query->result_array();

        return $course;
    }



	//审核
	public function set_user_disabled($uid, $disabled)
	{
		if ($this->db->update($this->db->dbprefix . $this->table,array('disabled'=>$disabled),array('id'=>$uid))){			
			return true;
		}else{
			return false;
		}

	}


	//
	public function examine_config($exa)
	{
		if ($this->db->update('nmp_config',array('info'=>$exa),array('name'=>'user_examine'))){			
			return true;
		}else{
			return false;
		}

	}



}




?>